import { Component, OnInit, OnDestroy } from '@angular/core'
import { Merchant, MerchantFull } from '@shared/interfaces/merchant'
import { deepCopy } from '@delon/util'
import { DataService } from '@shared/services/data.service'
import { MerchantStoreService } from '../../new/merchant-store.service'
import { ComWindow } from '@shared/classes/ComWindowClass'
import { MerchantNewTradeComponent } from '../../new/trade/trade.component'
import { INewPageColumn } from '@shared/interfaces/common'
import { MerchantService } from '../../merchant.service'
import { PageService } from '@shared/services/page.service'
import { NzMessageService } from 'ng-zorro-antd'
import { Router, ActivatedRoute } from '@angular/router'
import { encryptPassword } from 'app/utils/helpers'
import { I18NService } from '@core'

@Component({
  selector: 'app-merchant-edit-trade',
  templateUrl: './trade.component.html',
})
export class MerchantEditTradeComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  intMerCode: string

  constructor(
    private msg: NzMessageService,
    private pageService: PageService,
    private router: Router,
    private route: ActivatedRoute,
    private dataService: DataService,
    private merchantStoreService: MerchantStoreService,
    private merchantService: MerchantService,
    private i18n: I18NService,
  ) {}

  ngOnInit() {
    this.initData()
    this.initColumns()
  }

  ngOnDestroy() {
    this.merchantStoreService.reset()
  }

  initData(): void {
    const cloneMerchant: MerchantFull = deepCopy(this.dataService.merchant)
    this.merchantStoreService.updateValue(cloneMerchant)
    this.intMerCode = this.route.snapshot.params['id']
  }

  initColumns(): void {
    this.pages = [
      {
        component: new ComWindow(MerchantNewTradeComponent, { title: 'BIZ.MERCHANT.OTHER.TRADE.AUTH_CODE_RESET' }),
      },
    ]
  }

  submit(): void {
    const merchantFull = this.merchantStoreService.value
    let { authPassword } = merchantFull.merchant.common.tradeInfo
    authPassword = encryptPassword(authPassword)
    this.merchantService.updateAuthPassword(this.intMerCode, authPassword).subscribe(
      (isSuccess) => {
        this.pageService.triggerGuardAlive(false)
        this.merchantStoreService.reset()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.OPERATION_SUCCESS'))
        this.router.navigate(['..'], { relativeTo: this.route })
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.OPERATION_FAIL'))
      }
    )
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
